<template>
  <div class="address-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>地址管理</span>
          <el-button type="primary" size="large" @click="showAddAddressDialog">添加地址</el-button>
        </div>
      </template>
      <el-table :data="addresses" border style="width: 100%">
        <el-table-column prop="receiver" label="收货人" width="120"> </el-table-column>
        <el-table-column prop="contact" label="联系方式" width="120"> </el-table-column>
        <el-table-column prop="fullLocation" label="所在地区"> </el-table-column>
        <el-table-column prop="address" label="详细地址"> </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="changeAddress(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="small" @click="deleteAddress(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <addAddressDialog
      ref="addAddressDialogRef"
      @addressAdded="fetchAddresses"
      @getDataE="fetchAddresses"
    ></addAddressDialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { memberAddressGet } from '@/api/address.js'
import addressData from '@/assets/js/address'
import addAddressDialog from './addAddressDialog.vue'
import { memberAddressIdDelete } from '@/api/address'
import { ElMessage, ElMessageBox } from 'element-plus'

const addresses = ref([])
const fetchAddresses = async () => {
  const res = await memberAddressGet()
  addresses.value = res.data.result.map(item => {
    item.selected = false
    item.fullLocation = getAddress(item)
    return item
  })
}
const visible = ref(false)
defineExpose({ visible, fetchAddresses })
const getAddress = item => {
  let location = ''
  let tempItem = addressData
  const codes = [item.provinceCode, item.cityCode, item.countyCode]
  for (let i = 0; i < 3; i++) {
    const t = tempItem.find(t => t.code === codes[i])
    location += t.name
    tempItem = t.areaList
  }
  return location
}
const addAddressDialogRef = ref(null)
const showAddAddressDialog = () => {
  if (addAddressDialogRef.value) {
    addAddressDialogRef.value.sta = 0
    addAddressDialogRef.value.visible = true
  }
}
const changeAddress = data => {
  addAddressDialogRef.value.id = data.id
  addAddressDialogRef.value.sta = 1
  addAddressDialogRef.value.formData = { ...data }
  addAddressDialogRef.value.visible = true
  addAddressDialogRef.value.setInitPlace()
}

const deleteAddress = async id => {
  const confirmResult = await ElMessageBox.confirm('此操作将永久删除该地址, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).catch(err => err)
  if (confirmResult !== 'cancel') {
    try {
      const response = await memberAddressIdDelete(id)
      console.log(response.status)
      if (response.status === 200) {
        ElMessage.success('地址删除成功')
        await fetchAddresses()
      } else {
        ElMessage.error('删除地址失败，请稍后重试')
      }
    } catch (error) {
      ElMessage.error('删除地址时发生错误')
      console.error('Error deleting address:', error)
    }
  } else {
    ElMessage.info('删除操作已取消')
  }
}

fetchAddresses()
</script>
<style lang="scss">
.card-header .el-button--primary {
  background-color: rgb(39, 186, 155) !important;
  border-color: rgb(39, 186, 155) !important;
  color: white;
}
.el-table__body .el-button--primary {
  background-color: rgb(39, 186, 155) !important;
  border-color: rgb(39, 186, 155) !important;
  color: white;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .el-button--primary {
  margin-left: auto;
}
</style>
